package com.example.springsecuritydemo.service.impl;

import com.example.springsecuritydemo.service.MyService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @Classname: MyServiceImpl
 * @Description: 自定义方法实现权限控制实现类
 * @Date: 2021/3/17 22:14
 * @Created: by Wang Xu
 */
@Service
public class MyServiceImpl implements MyService {
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        // 拿到主体信息 数据库里面的/或者内存里面的
        Object principal = authentication.getPrincipal();

        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;

            // 拿到主体信息里面的权限列表 数据库里面的/或者内存里面的
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

            // 判断主体信息数(据库里面的/或者内存里面的) 是否包含 请求里面的uri
            return authorities.contains(new SimpleGrantedAuthority(request.getRequestURI()));
        }

        return false;
    }
}
